package com.mars.service;

import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.mars.common.RequestHolder;
import com.mars.dao.SysRoleAclMapper;
import com.mars.dao.SysRoleMapper;
import com.mars.dao.SysRoleUserMapper;
import com.mars.dao.SysUserMapper;
import com.mars.exception.ParamException;
import com.mars.param.RoleParam;
import com.mars.pojo.SysRole;
import com.mars.pojo.SysUser;
import com.mars.util.BeanValidator;
import com.mars.util.IpUtil;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author MARS
 * @date 2018/2/2
 */
@Service
public class SysRoleService {

    @Resource
    private SysRoleMapper sysRoleMapper;
    @Resource
    private SysRoleUserMapper sysRoleUserMapper;
    @Resource
    private SysRoleAclMapper sysRoleAclMapper;
    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private SysLogService sysLogService;

    public void save(RoleParam param) {
        // 校验字段
        BeanValidator.check(param);
        // 校验角色名称不能重复，目前角色属于但层级需要判断角色的唯一性
        if (checkExist(param.getName(),param.getId())) {
            throw new ParamException("角色名称已经存在");
        }

        SysRole sysRole = SysRole.builder().name(param.getName()).type(param.getType()).status(param.getStatus())
                .remark(param.getRemark()).build();

        sysRole.setOperator(RequestHolder.getCurrentUser().getUsername());
        sysRole.setOperateIp(IpUtil.getRemoteIp(RequestHolder.getCurrentRequest()));
        sysRole.setOperateTime(new Date());

        sysRoleMapper.insertSelective(sysRole);
        sysLogService.saveRoleLog(null,sysRole);
    }

    public void update(RoleParam param) {
        BeanValidator.check(param);
        if (checkExist(param.getName(),param.getId())) {
            throw new ParamException("角色名称已经存在");
        }

        // 校验before值,是否存在
        SysRole before = sysRoleMapper.selectByPrimaryKey(param.getId());
        Preconditions.checkNotNull(before,"待更新角色不存在");

        SysRole after = SysRole.builder().id(param.getId()).name(param.getName()).type(param.getType()).status(param.getStatus())
                .remark(param.getRemark()).build();
        after.setOperator(RequestHolder.getCurrentUser().getUsername());
        after.setOperateIp(IpUtil.getRemoteIp(RequestHolder.getCurrentRequest()));
        after.setOperateTime(new Date());

        sysRoleMapper.updateByPrimaryKeySelective(after);
        sysLogService.saveRoleLog(before,after);
    }

    // 获取所有角色
    public List<SysRole> getAll() {
        return sysRoleMapper.getAll();
    }

    private boolean checkExist(String name ,Integer id) {
        return sysRoleMapper.countByName(name,id) > 0 ;
    }

    // 通过用户id获取角色列表
    public List<SysRole> getRoleListByUserId(int userId) {
        // 获取角色id列表
        List<Integer> roleIdList = sysRoleUserMapper.getRoleIdListByUserId(userId);
        if (CollectionUtils.isEmpty(roleIdList)) {
            return Lists.newArrayList();
        }
        return sysRoleMapper.getByIdList(roleIdList);
    }

    public List<SysRole> getRoleListByAclId(int aclId) {
        // 获取角色id
        List<Integer> roleIdList = sysRoleAclMapper.getRoleIdListByAclId(aclId);
        if (CollectionUtils.isEmpty(roleIdList)) {
            return Lists.newArrayList();
        }
        return sysRoleMapper.getByIdList(roleIdList);
    }

    // 根据角色列表id获取对应的用户列表
    public List<SysUser> getUserListByRoleList (List<SysRole> roleList) {
        if (CollectionUtils.isEmpty(roleList)) {
            return Lists.newArrayList();
        }
        // 将roleList的id取出来做成一个列表
        List<Integer> roleIdList = roleList.stream().map(sysRole -> sysRole.getId()).collect(Collectors.toList());
        // 取出userId
        List<Integer> userIdList = sysRoleUserMapper.getUserIdListByRoleIdList(roleIdList);
        if (CollectionUtils.isEmpty(userIdList)) {
            return Lists.newArrayList();
        }

        // 获取对应用户
        return sysUserMapper.getByIdList(userIdList);
    }
}
